import cgi
import datetime
import wsgiref.handlers
import logging
import os

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import images
from google.appengine.ext.webapp import template

#logging.getLogger().setLevel(logging.DEBUG)


class MathExpr(db.Model):
  author = db.UserProperty()
  formula = db.StringProperty()
  value = db.StringProperty()
  public = db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    # Check if we are authenticated.
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Sign out'
      user_name = users.get_current_user()
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Sign in'
      user_name = None

    template_values = {
      'url': url,
      'url_linktext': url_linktext,
      'user_name' : user_name
      }
    # Print the footer
    path = os.path.join(os.path.dirname(__file__), 'header.html')
    self.response.out.write(template.render(path, template_values))

    path = os.path.join(os.path.dirname(__file__), 'post_formula.html')
    self.response.out.write(template.render(path, template_values))
    
    if users.get_current_user():
        query_str = "SELECT * FROM MathExpr WHERE author = :1 ORDER BY date DESC LIMIT 10"
        exprs = db.GqlQuery (query_str, users.get_current_user())
    else:
        query_str = "SELECT * FROM MathExpr WHERE public = 'YES' ORDER BY date DESC LIMIT 10"
        exprs = db.GqlQuery (query_str)
    
        
    exprs_values = {
        'exprs': exprs,
    }
    path = os.path.join(os.path.dirname(__file__), 'exprs.html')
    self.response.out.write(template.render(path, exprs_values))
     
    # Print the footer
    path = os.path.join(os.path.dirname(__file__), 'footer.html')
    self.response.out.write(template.render(path, template_values))

class Formula(webapp.RequestHandler):
  def post(self):
    if self.request.get("formula") != "" and self.request.get("value") != "" and self.request.get("value") != "undefined":
        expr = MathExpr()
        if users.get_current_user():
            expr.author = users.get_current_user()
        else:
            expr.public = 'YES'
        expr.formula = self.request.get("formula")
        #
        # Compute value of expression
        expr.value = self.request.get("value")
	if expr.value == 'Infinity':
	    expr.value = 'oo'
        expr.put()
    else:
        expr = MathExpr()
        expr.public = 'ERROR'
        expr.formula = self.request.get("formula")
        expr.value = self.request.get("value")
        expr.put()
    self.redirect('/')

class NullPage(webapp.RequestHandler):
  def post(self):
    self.redirect('/')
  def get(self):
    self.redirect('/')
    
class Features(webapp.RequestHandler):
  def get(self):
    # Check if we are authenticated.
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Sign out'
      user_name = users.get_current_user()
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Sign in'
      user_name = None

    template_values = {
      'url': url,
      'url_linktext': url_linktext,
      'user_name' : user_name
      }
    # Print the footer
    path = os.path.join(os.path.dirname(__file__), 'header.html')
    self.response.out.write(template.render(path, template_values))

    path = os.path.join(os.path.dirname(__file__), 'post_formula.html')
    self.response.out.write(template.render(path, template_values))

    # Print the content
    path = os.path.join(os.path.dirname(__file__), 'features.html')
    self.response.out.write(template.render(path, template_values))
     
    # Print the footer
    path = os.path.join(os.path.dirname(__file__), 'footer.html')
    self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/math', Formula),
  ('/features', Features),
  ('/*', NullPage)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
